#!/usr/bin/env node

const https = require('https'),
      http = require('http'),
      url = require('url'),
      cheerio = require('cheerio'),
      fs = require('fs'),
      addr = 'https://maoyan.com/films?showType=3';

let opt = url.parse(addr);
opt.headers = {
  'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36',
  'cookie':'uuid_n_v=v1; uuid=97BA6BC01CB411EB9E99A582304AF415204B11AA6C8A41EE82E6FA8F53BB57DB; _lxsdk_cuid=17586d2add64-0ecc917366b2ee-303464-e1000-17586d2add7a9; _lxsdk=97BA6BC01CB411EB9E99A582304AF415204B11AA6C8A41EE82E6FA8F53BB57DB; _csrf=1464c649b11748c65a7e48bff9c14c437aad9fe7afb62f63a1c362eeca07e5f4; Hm_lvt_703e94591e87be68cc8da0da7cbd0be2=1604299365,1604402874; Hm_lpvt_703e94591e87be68cc8da0da7cbd0be2=1604413312; __mta=150191625.1604284775172.1604403421557.1604413312764.7; _lxsdk_s=1758e7c4ba0-f43-e78-b2d%7C%7C2',
  'Sec-Fetch-Dest':'document',
  'Sec-Fetch-Mode':'navigate',
  'Sec-Fetch-Site':'cross-site',
  'Sec-Fetch-User':'?1'
};  

var message = [];
https.get(opt,(res)=>{
  let data = '';

  res.on('data',(chunk)=> data += chunk);

  res.on('end',()=>{
    let $ = cheerio.load(data);
    let name = $('body').find('div.movies-list dd');
    
    for(let i = 0 ; i<name.length; i++){
      let str = $(name[i]).find('.channel-detail>a').attr('href');
      let id = str.slice(7);
      let movieName = $(name[i]).find('.channel-detail a').text();
      let grade = ''+$(name[i]).find('.channel-detail .integer').text()+$(name[i]).find('.channel-detail .fraction').text();
      if(grade === ''){
        grade = '暂无评分';
      }

      var msg = {
        'movieId':id,
        'movieName':movieName,
        'movieRange':grade
      };
      message.push(msg);
    }
    console.log(message);
  });
});

http.createServer((req,res)=>{
  let html = fs.readFileSync('./index.html').toString('utf8');

  if(req.url === '/'){
    res.writeHead(200,{
      'Content-type':'text/html'          
    });
    res.end(html);   
  }
  else if(req.url === '/getlist'){
    res.end(JSON.stringify(message));
  }
}).listen(8080);




